package com.mxchip.livestarmobile.mobile.ui.dial

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import com.mxchip.livestarmobile.mobile.CallActivityA
import com.mxchip.livestarmobile.R
import com.mxchip.livestarmobile.mobile.ui.GroupCall
import com.mxchip.livestarmobile.mobile.ui.P2PSingleCall
import com.mxchip.livestarmobile.mobile.base.toast
import kotlinx.android.synthetic.main.fragment_dial.*

class DialFragment : Fragment() {

    private val dialViewModel by activityViewModels<DialViewModel>()

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onCreateView(inflater: LayoutInflater,
                              container: ViewGroup?, savedInstanceState: Bundle?): View? {

        return inflater.inflate(R.layout.fragment_dial, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dialViewModel.dialNumber.observe(viewLifecycleOwner, Observer { text_dial.text = it })

        arrayOf(
                button_dial_1, button_dial_2, button_dial_3,
                button_dial_4, button_dial_5, button_dial_6,
                button_dial_7, button_dial_8, button_dial_9,
                button_dial_asterisk, button_dial_0, button_dial_pound
        ).forEach {
            it.setOnClickListener { view ->
                val digit = view.tag as String
                dialViewModel.appendDigit(digit)
            }
        }

        button_dial_delete.setOnClickListener {
            dialViewModel.removeLastDigit()
        }

        button_dial_delete.setOnLongClickListener {
            dialViewModel.clearAllDigits()
            true
        }

        button_dial_call.setOnClickListener {
            try {
                val call = dialViewModel.makeCall()
                val callString = when (call) {
                    is P2PSingleCall ->
                        call.number
                    is GroupCall ->
                        call.groupNumber

                    else ->
                        throw IllegalStateException("call is Unknow type")
                }
                dialViewModel.createCallLog(callString)

                context?.let { CallActivityA.open(it, call) }
            } catch (t: Throwable) {
                t.message?.let { toast(it) }
            }
        }
    }
}